package com.dayuanit.pay.bank.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dayuanit.pay.bank.factory.PayHandlerFactory;
import com.dayuanit.pay.bank.handler.PayBaseHandler;
import com.dayuanit.pay.dao.PayOrderDao;
import com.dayuanit.pay.domain.PayOrder;
import com.dayuanit.pay.mallenum.PayStatus;
import com.dayuanit.pay.service.RedisService;

@Component("sinaOrderQueryTask")
public class SinaOrderQueryTask {
	
	private static final Logger logger = LoggerFactory.getLogger(SinaOrderQueryTask.class);
	
	@Autowired
	private PayHandlerFactory payHandlerFactory;
	
	@Autowired
	private PayOrderDao payOrderDao;
	
	@Autowired
	private RedisService redisService;
	
	private final static int PRE_NUM = 10;
	
	public void doTask() {
		
		logger.info("支付订单定时查询开始...");
		int off = 0;
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, -10);
		Date startTime = cal.getTime();
		
		cal.add(Calendar.MINUTE, -33);
		Date endTime = cal.getTime();
		
		List<PayOrder> list = null;
		do {
			list = payOrderDao.listUnPayOrder(startTime, endTime, off, PRE_NUM);
			process(list);
			off += PRE_NUM;
		} while(null != list && list.size() > 0);
		
		logger.info("支付订单定时查询结束...");
	}
	
	private void process(List<PayOrder> list) {
		for (PayOrder order : list) {
			PayBaseHandler payHandler = payHandlerFactory.getHandler(order.getPayChannel());
			try {
				boolean success = payHandler.orderSearch(order);
				if (!success) {
					continue;
				}
				
				payOrderDao.updatePayStatus(order.getId(), PayStatus.ALREADY_PAID.getStatus(), order.getStatus());
				
				//bizId$payId
				redisService.addPayedOrder(order.getBizId() + "$" +  String.valueOf(order.getId()));
			} catch (Exception e) {
				logger.error("查询新浪支付订单异常，{}, 订单号{}",e.getMessage(), order.getId(), e);
				continue;
			}
		}
	}

}
